﻿$(function () {
    loadUserList();
    bindEvent();
    startListen();
})
function startListen() {
    var myListener = new listener({ interval: 4000, listenKey: $("#hdIdentity").val() }, onListening);
    myListener.start();
}

function bindEvent() {
    $("#uluserList li").live("click", function () {
        onUserClick(this);
    });
    $("#btnCommit").bind("click", function () {
        commitMessage();
    });
}
function commitMessage() {
    var message = { from: $("#hdIdentity").val(), to: $("#slTalkTo").val(), body: $("#txtComment").val() };
    $.ajax({ type: "post", url: "/aspnet/service/PostCommentHandler.ashx", data: message, async: true });
}

function loadUserList() {
    $.get("/aspnet/service/UserListHandler.ashx", function (data) {
        var users = eval(data);
        var len = users.length;
        var userFragment = document.createDocumentFragment();
        for (var i = 0; i < len; i++) {
            userFragment.appendChild(createUserList(users[i].Key));
        }
        document.getElementById("uluserList").appendChild(userFragment);
        updateUserListTitle(len);
    });
}

function updateUserListTitle(num) {
    $("#spUserNums").html(num);
}

function onListening(eventData) {
    $("#publicWindow").append(eventData+"<br/>");
}

function onUserClick(userNode) {
    var userObj = { value: $(userNode).attr("key"), name: $(userNode).text() };
    var queryPath = "#slTalkTo option[value='" + userObj.value + "']";
    var option = $(queryPath);
    if (option.get(0) == undefined) {
        $("#slTalkTo").append("<option value='" + userObj.value + "'>" + userObj.name + "</option>");
    }
    $("#slTalkTo").val(userObj.value);
}

function createUserList(userData) {
    var li = document.createElement("li");
    var textNode = document.createTextNode(userData.substr(0, 8));
    li.appendChild(textNode);
    var attr = document.createAttribute("key");
    attr.value = userData;
    li.setAttributeNode(attr);
    return li;
}

function createMessageSpan(message) {
    var span = document.createElement("span");
    var textNode = document.createTextNode(message);
    span.appendChild(textNode);
    return span;
}

function listener(options, callback) {
    //interval time
    this.listenKey = options.listenKey||"";
    this.interval = options.interval || 1000;
    this.url = options.url || "/aspnet/service/ListenHandler.ashx";
    this.callBack = callback;
    that = this;
}
listener.prototype.start = function () {
    setInterval(function () {
        $.get(that.url, { listenKey: that.listenKey }, that.callBack);
    }, that.interval);
}